package gatoropoly.game.action;

import gatoropoly.game.Gatoropoly;
import gatoropoly.game.Game;
import modelz.UpdateListener;

public class StartGameAction extends GatoropolyClientAction {

	private Game game;

	private UpdateListener<Game> gameListener = new UpdateListener<Game>() {
		public void updated(Game item) {
			update();
		}
	};

	public StartGameAction(Gatoropoly client) {
		super(client, "Start Game");
	}

	public void perform() {
		client.startGame();
	}

	public boolean canPerform() {
		if (!super.canPerform())
			return false;

		Game game = self().getGame();
		if( game == null || game.getStatus()!=Game.Status.CONFIG || !self().equals(game.getMaster()) )
			return false;
		
		return game.getMinPlayers() <= game.getPlayers() && game.getPlayers() <= game.getMaxPlayers(); 
	}

	@Override
	public void update() {
		Game newGame = self().getGame();
		if (newGame == null || !newGame.equals(game)) {
			if (game != null)
				game.removeListener(gameListener);

			game = newGame;

			if (game != null)
				game.addListener(gameListener);
		}
		super.update();
	}

}
